<template>
	<div class="default-main">

		<!-- 按钮区 -->
		<el-affix v-if="isAdmin()" :offset="80" position="top" target=".default-main">
			<el-button icon="el-icon-Plus" type="primary" @click="toAdd">新增</el-button>
			<el-button icon="el-icon-Refresh" type="primary" @click="refresh">刷新</el-button>
		</el-affix>

		<div v-for="(productGroup, index) in allProductGroup" v-if="allProductGroup.length > 0">
			<el-divider :style="{'margin-top':index === 0 ? undefined : '50px'}" content-position="left">{{
					productGroup.classificationNameList.join('&nbsp;/&nbsp;')
				}}
			</el-divider>
			<ul class="product-list">
				<li v-for="product in productGroup.productList">
					<el-card>
						<template #header>
							<div style="text-align: center">
								<el-tooltip :content="product.productName" :show-after="500" placement="top" width="auto">
									<el-text :line-clamp="1" style="cursor: pointer" type="primary" @click="showProductDetail(productGroup, product)">{{
											product.productName
										}}
									</el-text>
								</el-tooltip>
							</div>
						</template>
						<el-image :src="getImage(product.image!)" class="image" fit="contain" lazy @click="showProductDetail(productGroup, product)"></el-image>
						<template v-if="isAdmin()" #footer>
							<el-button icon="el-icon-Edit" size="small" type="primary" @click="toEdit(product)">编辑</el-button>
							<el-popconfirm :hide-after="0" :title="`删除该商品（${product.productName}）？`" confirm-button-type="danger" width="auto"
							               @confirm="deleteProduct(product)">
								<template #reference>
									<el-button v-auth="'g-product:deleteProduct'" icon="el-icon-Delete" size="small" type="danger">删除</el-button>
								</template>
							</el-popconfirm>
						</template>
					</el-card>
				</li>
			</ul>
		</div>

		<el-empty v-else :image-size="400"/>

		<!-- 对话框（新增、修改） -->
		<el-dialog v-model="dialogVisible.edit" :close-on-click-modal="false" :close-on-press-escape="true" :title="dialogTitle"
		           append-to-body center class="cus-dialog" destroy-on-close draggable width="50%">
			<div v-if="productImage" class="cus-center" style="padding-bottom: 20px">
				<el-image :src="getImage(productImage)" fit="contain" style="width: 128px; height: 128px"></el-image>
			</div>
			<el-form ref="editFormRef" :model="saveProductRequest" :rules="rules" label-width="auto">
				<el-form-item label="名称" prop="productName">
					<el-input v-model="saveProductRequest.productName" clearable></el-input>
				</el-form-item>
				<el-row :gutter="20" justify="start">
					<el-col :span="12">
						<el-form-item label="类别" prop="classificationId">
							<el-cascader
									v-model="saveProductRequest.classificationId"
									:options="classificationOptionList"
									:props="{ expandTrigger: 'hover', checkStrictly: false, emitPath: false }"
									:show-all-levels="true"
									clearable
									filterable
							></el-cascader>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="同级排序" prop="sort">
							<el-input-number v-model="saveProductRequest.sort" :max="MAX_INTEGER" :min="1" :step="1" class="w100" step-strictly></el-input-number>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="图片" prop="image">
					<el-input v-model="saveProductRequest.image" clearable></el-input>
				</el-form-item>
				<cus-table-title label="成本" style="margin-top: 50px">
					<template #after>
						<el-button icon="el-icon-Plus" size="small" style="margin-left: 20px" type="primary" @click="addRequirementElement">添加</el-button>
					</template>
				</cus-table-title>
				<el-form-item prop="requirementList">
					<el-table v-loading="requirementTableLoading" :data="saveProductRequest.requirementList" border class="cus-table" fit highlight-current-row>
						<el-table-column align="center" label="序号" type="index" width="60"></el-table-column>
						<el-table-column align="center" label="物品" min-width="200" prop="elementId">
							<template v-slot="scope">
								<el-select v-model="scope.row.elementId" clearable filterable @change="selectedRequiredItemChanged($event, scope.row)">
									<el-option v-for="item in itemList" :key="scope.$index + 'itemId_' + item.id" :label="item.itemName" :value="item.id">
										<div style="display: flex;justify-content: space-between">
											<div>{{ item.itemName }}</div>
											<div v-if="item.image">
												<el-image :src="getImage(item.image)" fit="contain" style="width: 30px; height: 30px"></el-image>
											</div>
										</div>
									</el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column align="center" label="数量" min-width="200" prop="quantity">
							<template v-slot="scope">
								<el-input-number v-model="scope.row.quantity" :max="MAX_INTEGER" :min="1" :step="1" class="w100"></el-input-number>
							</template>
						</el-table-column>
						<el-table-column :label="String($t('table.actions'))" :width="120" align="center" fixed="right">
							<template v-slot="scope">
								<el-button icon="el-icon-Delete" size="small" type="danger" @click="removeRequirementElement(scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
				<cus-table-title label="解锁" style="margin-top: 50px">
					<template #after>
						<el-button icon="el-icon-Plus" size="small" style="margin-left: 20px" type="primary" @click="addUnlockElement">添加</el-button>
					</template>
				</cus-table-title>
				<el-form-item prop="unlockList">
					<el-table ref="unlockTableRef" v-loading="unlockTableLoading" :data="saveProductRequest.unlockList" border class="cus-table" fit
					          highlight-current-row>
						<el-table-column align="center" label="序号" type="index" width="60"></el-table-column>
						<el-table-column align="center" label="类型" prop="type" width="200">
							<template v-slot="scope">
								<business-code-select v-model="scope.row.type" clearable code-type="productUnlockType"
								                      @change="unlockTypeChanged($event, scope.row)"></business-code-select>
							</template>
						</el-table-column>
						<el-table-column align="center" label="解锁项" min-width="200">
							<template v-slot="scope">
								<!-- 物品 -->
								<div v-if="scope.row.type === 'ITEM'">
									<el-select v-model="scope.row.elementId" clearable filterable @change="selectedUnlockItemChanged($event, scope.row)">
										<el-option v-for="item in itemList" :key="scope.$index + 'itemId_' + item.id" :label="item.itemName" :value="item.id">
											<div style="display: flex;justify-content: space-between">
												<div>{{ item.itemName }}</div>
												<div v-if="item.image">
													<el-image :src="getImage(item.image)" fit="contain" style="width: 30px; height: 30px"></el-image>
												</div>
											</div>
										</el-option>
									</el-select>
								</div>
								<!-- 建筑 -->
								<div v-if="scope.row.type === 'BUILDING'">
									<el-select v-model="scope.row.elementId" clearable filterable value-key="id" @change="selectedUnlockBuildingChanged($event, scope.row)">
										<el-option v-for="building in buildingList" :key="scope.$index + 'buildingId_' + building.id" :label="building.buildingName"
										           :value="building.id">
											<div style="display: flex;justify-content: space-between">
												<div>{{ building.buildingName }}</div>
												<div v-if="building.image">
													<el-image :src="getImage(building.image)" fit="contain" style="width: 30px; height: 30px"></el-image>
												</div>
											</div>
										</el-option>
									</el-select>
								</div>
								<!-- 文本 -->
								<div v-if="scope.row.type === 'TEXT'" class="cus-center">
									<el-input v-model="scope.row.content" :autosize="{ minRows: 1, maxRows: 4}" clearable maxlength="500" type="textarea"></el-input>
								</div>
							</template>
						</el-table-column>
						<el-table-column :label="String($t('table.actions'))" :width="120" align="center" fixed="right">
							<template v-slot="scope">
								<el-button icon="el-icon-Delete" size="small" type="danger" @click="removeUnlockElement(scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button v-auth="'g-product:saveProduct'" icon="el-icon-CircleCheck" type="primary" @click="save">
					保存
				</el-button>
				<el-button icon="el-icon-CircleClose" type="warning" @click="dialogVisible.edit = false">
					取消
				</el-button>
			</template>
		</el-dialog>

		<!-- 对话框（查看商品详情，只读） -->
		<el-dialog v-model="dialogVisible.view" :close-on-click-modal="false" :close-on-press-escape="true" :title="viewDialogTitle"
		           append-to-body center class="cus-dialog" destroy-on-close draggable width="50%">
			<div v-if="productImage" class="cus-center" style="padding-bottom: 20px">
				<el-image :src="getImage(productImage)" fit="contain" style="width: 128px; height: 128px"></el-image>
			</div>
			<el-form :model="productVo" label-width="auto">
				<el-row :gutter="20" justify="space-evenly">
					<el-col :span="6">
						<el-form-item label="名称">
							<el-tag>{{ productVo.productName }}</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="类别">
							<el-tag>{{ productVo.classificationNameList.join('&nbsp;/&nbsp;') }}</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
				<cus-table-title v-if="productVo.requirementVoList && productVo.requirementVoList.length > 0" label="成本"></cus-table-title>
				<el-form-item v-if="productVo.requirementVoList && productVo.requirementVoList.length > 0">
					<el-table v-loading="requirementVoTableLoading" :data="productVo.requirementVoList" border class="cus-table" fit highlight-current-row>
						<el-table-column align="center" label="序号" type="index" width="60"></el-table-column>
						<el-table-column align="center" label="物品" min-width="200">
							<template v-slot="scope">
								<el-space>
									<el-link :underline="false" type="primary" @click="showItemDetail(scope.row.elementId)">{{ getItemName(scope.row.elementId) }}</el-link>
									<el-image v-if="scope.row.image" :src="getImage(scope.row.image)" fit="contain" style="width: 50px; height: 50px; cursor: pointer"
									          @click="showItemDetail(scope.row.elementId)"></el-image>
								</el-space>
							</template>
						</el-table-column>
						<el-table-column align="center" label="数量" width="150">
							<template v-slot="scope">
								<el-tag>{{ scope.row.quantity }}</el-tag>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
				<cus-table-title v-if="productVo.unlockVoList && productVo.unlockVoList.length > 0" label="解锁"></cus-table-title>
				<el-form-item v-if="productVo.unlockVoList && productVo.unlockVoList.length > 0">
					<el-table ref="unlockViewTableRef" v-loading="unlockVoTableLoading" :data="productVo.unlockVoList" border class="cus-table" fit
					          highlight-current-row>
						<el-table-column align="center" label="序号" type="index" width="60"></el-table-column>
						<el-table-column align="center" label="类型" prop="type" width="150">
							<template v-slot="scope">
								<el-tag>{{ scope.row.type === 'TEXT' ? '其他' : getBusinessCodeName('productUnlockType', scope.row.type) }}</el-tag>
							</template>
						</el-table-column>
						<el-table-column align="center" label="解锁项" min-width="200">
							<template v-slot="scope">
								<!-- 物品 -->
								<div v-if="scope.row.type === 'ITEM'">
									<el-space>
										<el-link :underline="false" type="primary" @click="showItemDetail(scope.row.elementId)">{{ getItemName(scope.row.elementId) }}</el-link>
										<el-image v-if="scope.row.image" :src="getImage(scope.row.image)" fit="contain" style="width: 50px; height: 50px; cursor: pointer"
										          @click="showItemDetail(scope.row.elementId)"></el-image>
									</el-space>
								</div>
								<!-- 建筑 -->
								<div v-if="scope.row.type === 'BUILDING'">
									<el-space>
										<el-link :underline="false" type="primary" @click="showBuildingDetail(scope.row.elementId)">{{
												getBuildingName(scope.row.elementId)
											}}
										</el-link>
										<el-image v-if="scope.row.image" :src="getImage(scope.row.image)" fit="contain" style="width: 50px; height: 50px; cursor: pointer"
										          @click="showBuildingDetail(scope.row.elementId)"></el-image>
									</el-space>
								</div>
								<!-- 文本 -->
								<div v-if="scope.row.type === 'TEXT'">
									<el-text class="pre-wrap">{{ scope.row.content }}</el-text>
								</div>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button icon="el-icon-CircleClose" type="warning" @click="dialogVisible.view = false">
					关闭
				</el-button>
			</template>
		</el-dialog>

		<!-- 对话框（物品详情） -->
		<cus-item-dialog v-model:visible="dialogVisible.item" :item-id="itemIdDisplayed"/>

		<!-- 对话框（建筑详情） -->
		<cus-building-dialog v-model:visible="dialogVisible.building" :building-id="buildingIdDisplayed"/>

	</div>
</template>

<script lang="ts" name="AwesomeStore" setup>

import {reactive, ref, watch} from 'vue'
import {focusFormErrorElement, getBusinessCodeName, getImage, messageError, messageSuccess} from '@/utils/commonUtil'
import {isAdmin} from '@/utils/authUtil'
import {MAX_INTEGER} from '@/utils/constantsUtil'
import {type FormInstance, type FormRules, type TableInstance} from 'element-plus'
import {cloneDeep} from 'lodash-es'
import CusTableTitle from '@/components/cus-table-title.vue'
import {useI18n} from 'vue-i18n'
import CusBuildingDialog from '@/components/cus-building-dialog.vue'
import CusItemDialog from '@/components/cus-item-dialog.vue'
import BusinessCodeSelect from '@/components/business-code-select.vue'
import {getAllProductionBuildingApi} from '@/api/gameData/recipe.api'
import {useRoute} from 'vue-router'
import {
	deleteProductApi,
	getAllBuildingApi,
	getAllItemApi,
	getAllProductGroupApi,
	getAllProductRequirementByProductIdApi,
	getAllProductRequirementVoByProductIdApi,
	getAllProductUnlockByProductIdApi,
	getAllProductUnlockVoByProductIdApi,
	getAllRecipeApi,
	getProductCascadeClassificationApi,
	getRecipeDetailByIdApi,
	saveProductApi
} from '@/api/gameData/product.api'

const {t} = useI18n()

const editFormRef = ref<FormInstance>()
const unlockTableRef = ref<TableInstance>()
const unlockViewTableRef = ref<TableInstance>()

const popoverRefVisible = ref(false)
const popoverViewRefVisible = ref(false)
const recipeDetailLoading = ref(false)
const recipeVo = reactive<SearchRecipeVo & SaveRecipeRequest>({
	recipeId: undefined,
	recipeName: undefined,
	recipeNameDisplayed: undefined,
	productType: 1,
	sort: MAX_INTEGER,
	materialList: [],
	productList: [],
	buildingProduct: undefined,
	buildingList: []
})

const allProductGroup = reactive<ProductGroupVo[]>([])

const productVo = reactive<GProductVo>({
	id: undefined,
	productName: undefined,
	classificationId: undefined,
	classificationNameList: [],
	image: undefined,
	sort: undefined,
	requirementVoList: [],
	unlockVoList: []
})

const saveProductRequest = reactive<SaveProductRequest>({
	id: undefined,
	productName: '',
	classificationId: 0,
	image: '',
	sort: 1,
	requirementList: [],
	unlockList: []
})

const itemList = reactive<GItem[]>([])
const buildingList = reactive<GBuilding[]>([])
const productionBuildingOptionList = reactive<GBuilding[]>([])
const classificationOptionList = reactive<CascadeClassificationVo[]>([])
const recipeList = reactive<GRecipe[]>([])

const rules = reactive<FormRules>({
	productName: [
		{required: true, message: '请输入商品名称', trigger: 'change'}
	],
	classificationId: [
		{required: true, message: '请选择商品类别', trigger: 'change', type: 'number'}
	],
	image: [
		{required: true, message: '请输入商品图片', trigger: 'change'}
	],
	sort: [
		{required: true, message: '请输入商品同级排序', trigger: 'change'}
	],
	requirementList: [
		{required: false, message: '请添加商品成本', trigger: 'change', type: 'array'}
	],
	unlockList: [
		{required: false, message: '请添加商品解锁项', trigger: 'change', type: 'array'}
	]
})

const dialogVisible = reactive({
	edit: false,
	view: false,
	item: false,
	building: false
})
const dialogTitle = ref('')
const viewDialogTitle = ref('')
const productImage = ref('')

const itemIdDisplayed = ref<number>()
const buildingIdDisplayed = ref<number>()

const showItemDetail = (itemId: number) => {
	itemIdDisplayed.value = itemId
	dialogVisible.item = true
}

const showBuildingDetail = (buildingId: number) => {
	buildingIdDisplayed.value = buildingId
	dialogVisible.building = true
}

const getItemName = (itemId: number) => {
	return itemList.find(item => item.id === itemId)?.itemName
}

const getBuildingName = (buildingId: number) => {
	return buildingList.find(building => building.id === buildingId)?.buildingName
}

const getRecipeName = (recipeId: number) => {
	return recipeList.find(recipe => recipe.id === recipeId)?.recipeName
}

const resetRecipe = (productType?: SaveRecipeRequest['productType']) => {
	recipeVo.recipeId = undefined
	recipeVo.recipeName = undefined
	recipeVo.recipeNameDisplayed = undefined
	recipeVo.productType = productType ?? 1
	recipeVo.sort = MAX_INTEGER
	recipeVo.materialList = []
	recipeVo.productList = []
	recipeVo.buildingProduct = undefined
	recipeVo.buildingList = []
}

const showRecipeDetail = (recipeId: number, isView: boolean = false) => {
	recipeDetailLoading.value = true
	getRecipeDetailByIdApi(recipeId).then(response => {
		const searchRecipeVo = response.data
		if (searchRecipeVo.buildingVo) {
			resetRecipe(2)
		} else {
			resetRecipe()
		}
		Object.assign(recipeVo, JSON.parse(JSON.stringify(searchRecipeVo)))
		for (const material of recipeVo.materialList!) {
			Reflect.set(material, 'item', {
				id: material.itemId,
				itemName: material.itemName
			})
		}
		if (searchRecipeVo.buildingVo) {
			Reflect.set(recipeVo, 'buildingProduct', {
				id: searchRecipeVo.buildingVo.buildingId!,
				buildingName: searchRecipeVo.buildingVo.buildingName!,
				power: searchRecipeVo.buildingVo.power
			})
		} else {
			for (const product of recipeVo.productList) {
				Reflect.set(product, 'item', {
					id: product.itemId,
					itemName: product.itemName
				})
			}
			for (const building of recipeVo.buildingList) {
				Reflect.set(building, 'building', {
					id: building.buildingId,
					buildingName: building.buildingName
				})
				Reflect.set(building, 'power', building.power === 0 ? '/' : building.power)
				Reflect.set(building, 'overclockable', building.overclockable === 1 ? '能' : '不能')
			}
		}
		recipeDetailLoading.value = false
	})
	if (isView) {
		popoverViewRefVisible.value = true
	} else {
		popoverRefVisible.value = true
	}
}

const resetProductVo = () => {
	productVo.id = undefined
	productVo.productName = undefined
	productVo.classificationId = undefined
	productVo.image = undefined
	productVo.sort = undefined
	productVo.requirementVoList = []
	productVo.unlockVoList = []
}

const showProductDetail = (productGroup: ProductGroupVo, product: GProduct) => {
	requirementVoTableLoading.value = true
	unlockVoTableLoading.value = true
	resetProductVo()
	Object.assign(productVo, JSON.parse(JSON.stringify(product)))
	productVo.classificationNameList = productGroup.classificationNameList
	productImage.value = product.image!
	viewDialogTitle.value = product.productName!
	// 获取成本项和解锁项
	getAllProductRequirementVoByProductIdApi(productVo.id!).then(response => {
		productVo.requirementVoList = response.data
	}).finally(() => {
		requirementVoTableLoading.value = false
	})
	getAllProductUnlockVoByProductIdApi(productVo.id!).then(response => {
		productVo.unlockVoList = response.data
	}).finally(() => {
		unlockVoTableLoading.value = false
	})
	dialogVisible.view = true
}

const resetSaveProductRequest = () => {
	saveProductRequest.id = undefined
	saveProductRequest.productName = ''
	saveProductRequest.classificationId = 0
	saveProductRequest.image = ''
	saveProductRequest.sort = 1
	saveProductRequest.requirementList = []
	saveProductRequest.unlockList = []
}

const requirementTableLoading = ref(false)
const unlockTableLoading = ref(false)

const requirementVoTableLoading = ref(false)
const unlockVoTableLoading = ref(false)

const toAdd = () => {
	resetSaveProductRequest()
	productImage.value = ''
	dialogTitle.value = '新增商品'
	dialogVisible.edit = true
}

const toEdit = (row: GProduct) => {
	resetSaveProductRequest()
	Object.assign(saveProductRequest, cloneDeep(row))
	productImage.value = row.image!
	// 查询成本项
	requirementTableLoading.value = true
	getAllProductRequirementByProductIdApi(row.id!).then(response => {
		saveProductRequest.requirementList = response.data
	}).finally(() => {
		requirementTableLoading.value = false
	})
	// 查询解锁项
	unlockTableLoading.value = true
	getAllProductUnlockByProductIdApi(row.id!).then(response => {
		saveProductRequest.unlockList = response.data
	}).finally(() => {
		unlockTableLoading.value = false
	})
	dialogTitle.value = '编辑商品'
	dialogVisible.edit = true
}

const addRequirementElement = () => {
	saveProductRequest.requirementList.push({
		id: undefined,
		type: 'ITEM',
		elementId: undefined,
		quantity: undefined
	})
	editFormRef.value?.validateField('requirementList').catch(() => {
	})
}

const removeRequirementElement = (row: GProductRequirement) => {
	saveProductRequest.requirementList.splice(saveProductRequest.requirementList.indexOf(row), 1)
	editFormRef.value?.validateField('requirementList').catch(() => {
	})
}

const selectedRequiredItemChanged = (itemId: number | undefined, row: GProductRequirement) => {
	if (!itemId) {
		row.elementId = undefined
		row.quantity = undefined
	}
}

const addUnlockElement = () => {
	saveProductRequest.unlockList.push({
		id: 0,
		type: undefined,
		elementId: undefined,
		content: undefined
	})
	editFormRef.value?.validateField('unlockList').catch(() => {
	})
}

const removeUnlockElement = (row: GProductUnlock) => {
	saveProductRequest.unlockList.splice(saveProductRequest.unlockList.indexOf(row), 1)
	editFormRef.value?.validateField('unlockList').catch(() => {
	})
}

const unlockTypeChanged = (unlockType: GProductUnlock['type'], row: GProductUnlock) => {
	row.elementId = undefined
	row.content = undefined
}

const selectedUnlockItemChanged = (itemId: number | undefined, row: GProductUnlock) => {
	if (!itemId) {
		row.elementId = undefined
		row.content = undefined
	}
}

const selectedUnlockBuildingChanged = (buildingId: number | undefined, row: GProductUnlock) => {
	if (!buildingId) {
		row.elementId = undefined
		row.content = undefined
	}
}

const selectedUnlockRecipeChanged = (recipeId: number | undefined, row: GProductUnlock) => {
	if (!recipeId) {
		row.elementId = undefined
		row.content = undefined
	}
}

const save = () => {
	editFormRef.value!.validate(isValid => {
		if (isValid) {
			// 字段校验
			for (const requirement of saveProductRequest.requirementList) {
				if (!requirement.type) {
					messageError('成本项类型不能为空')
					return
				}
				if (!requirement.elementId) {
					messageError('请选择成本项')
					return
				}
				if (!requirement.quantity) {
					messageError('请填写成本项数量')
					return
				}
			}
			for (const unlock of saveProductRequest.unlockList) {
				if (!unlock.type) {
					messageError('解锁项类型不能为空')
					return
				}
				switch (unlock.type) {
					case 'ITEM':
						if (!unlock.elementId) {
							messageError('请选择解锁项物品')
							return
						}
						break
					case 'BUILDING':
						if (!unlock.elementId) {
							messageError('请选择解锁项建筑')
							return
						}
						break
					case 'TEXT':
						if (!unlock.content) {
							messageError('请填写解锁项文本')
							return
						}
						break
				}
			}
			saveProductApi(saveProductRequest).then(() => {
				if (saveProductRequest.id) {
					messageSuccess(t('successMessage.update'))
				} else {
					messageSuccess(t('successMessage.add'))
				}
				dialogVisible.edit = false
				initAllProduct()
			})
		} else {
			focusFormErrorElement()
		}
	})
}

const deleteProduct = (row: GProduct) => {
	deleteProductApi(row.id!).then(() => {
		messageSuccess(t('successMessage.delete'))
		initAllProduct()
	})
}

const refresh = () => {
	initOptions()
	initAllProduct()
}

const initAllProduct = () => {
	allProductGroup.length = 0
	getAllProductGroupApi().then(res => {
		allProductGroup.push(...res.data)
	})
}

const initOptions = () => {
	itemList.length = 0
	buildingList.length = 0
	recipeList.length = 0
	productionBuildingOptionList.length = 0
	classificationOptionList.length = 0
	getAllItemApi().then(response => {
		itemList.push(...response.data)
	})
	getAllBuildingApi().then(response => {
		buildingList.push(...response.data)
	})
	getAllRecipeApi().then(response => {
		recipeList.push(...response.data)
	})
	getAllProductionBuildingApi().then(response => {
		productionBuildingOptionList.push(...response.data)
	})
	getProductCascadeClassificationApi().then(response => {
		classificationOptionList.push(...response.data)
	})
}

const route = useRoute()

watch(() => route.path, () => {
	for (const key in dialogVisible) {
		dialogVisible[<keyof typeof dialogVisible>key] = false
	}
	popoverRefVisible.value = false
	popoverViewRefVisible.value = false
})

initOptions()
initAllProduct()

</script>

<style lang="scss" scoped>
.product-list {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(256px, 1fr));
	gap: 20px;
	list-style: none;

	.image {
		cursor: pointer;
	}
}

.popover-divider {
	:deep(.el-divider__text) {
		background: var(--el-popover-bg-color);
	}
}
</style>
